import { Controller, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { getManager, Repository, Transaction } from 'typeorm';
import { EmrDocTypeEntity } from '../entities/emr.doc.type.entity';
import { EmrDocTypeInput, Idoctype } from '../InterfaceBll/Idoctype';
import { EmrTeetEntity } from '../entities/emr.teet.entity';

@Injectable()
export class doctypeService implements Idoctype {
  constructor(
    @InjectRepository(EmrDocTypeEntity)
    public doctypeRepository: Repository<EmrDocTypeEntity>,

    @InjectRepository(EmrTeetEntity)
    public emrteeRepository: Repository<EmrTeetEntity>,
  ) {}

  async findAllText() {
    return await this.doctypeRepository.find();
  }

  async findOneTextById(id: string) {
    return await this.doctypeRepository.findOne(id);
  }

  async findByName(textname: string) {
    return await this.doctypeRepository.find({ TEXTNAME: textname });
  }

  async updateOne(doctype: EmrDocTypeInput): Promise<EmrDocTypeEntity> {
    let entity: EmrDocTypeEntity = new EmrDocTypeEntity();
    if (doctype) {
      entity.ID = doctype.ID.toString();
      entity.PARENTID = doctype.PARENTID.toString();
      entity.TEXTNAME = doctype.TEXTNAME.toString();
    }
    await this.doctypeRepository.update(entity.ID, entity);
    return entity;
  }

  async addOne(doctype: EmrDocTypeInput): Promise<EmrDocTypeEntity> {
    let entity: EmrDocTypeEntity = new EmrDocTypeEntity();
    if (doctype) {
      entity.ID = doctype.ID.toString();
      entity.PARENTID = doctype.PARENTID.toString();
      entity.TEXTNAME = doctype.TEXTNAME.toString();
    }
    await this.doctypeRepository.insert(entity);
    return entity;
  }

  async deleteOne(id: string): Promise<boolean> {
    try {
      await this.doctypeRepository.delete(id);
      return true;
    } catch (e) {
      return false;
    }
  }

  //业务过程处理
  async transactiontest(): Promise<boolean> {
    // await getManager().transaction(async (transactionManage) => {
    //   /*
    //    *业务过程的处理
    //    *  */
    //   //transactionManage.delete(EmrDocTypeEntity,id);
    //   // transactionManage.insert(EmrDocTypeEntity, { } );
      let tt1: EmrTeetEntity = new EmrTeetEntity();
      tt1.AA = '111111';
      tt1.BB = '测试测试';

      let tt2: EmrTeetEntity = new EmrTeetEntity();
      tt2.AA = '222222';
      tt2.BB = '测试测试123123';

    let tt3: EmrTeetEntity = new EmrTeetEntity();
    tt3.AA = '333333';
    tt3.BB = '测试测试333333';

    //
    //   transactionManage.insert(EmrTeetEntity, tt1);
    //   transactionManage.insert(EmrTeetEntity, tt2);
    // });
    // this.emrteeRepository.manager.transaction<EmrTeetEntity>(ii=>{
    //
    // })
    return true;
  }
}
